<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品配置</el-breadcrumb-item>
    </el-breadcrumb>

    <span>{{ detail.name }}【{{ detail.id }}】</span>
    <span>{{ detail.status.name }}</span>
    <div style="float: right">
      <span style="color: #999">创建人：</span>{{ detail.creator }}
    </div>
    <el-card>
      <el-descriptions>
        <el-descriptions-item label="商品类别">{{
          detail.class.name
        }}</el-descriptions-item>
        <el-descriptions-item label="商品类型">{{
          detail.type.name
        }}</el-descriptions-item>
        <el-descriptions-item label="统一价">
          <span style="color: red">{{ detail.stand_price }}</span>
          元
        </el-descriptions-item>
        <el-descriptions-item label="关联分类">{{
          detail.product_type_names
        }}</el-descriptions-item>
        <el-descriptions-item label="商品标签">{{
          detail.tags
        }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{
          detail.remark
        }}</el-descriptions-item>
      </el-descriptions>
    </el-card>
    <el-row>
      <el-button
        class="theme-background-color"
        size="medium"
        @click="openCommodityDialog"
        v-show="detail.status.id != 1"
        >编辑</el-button
      >
      <el-button
        size="medium"
        v-if="detail.status.id == 2 || detail.status.id == 0"
        @click="enable"
        >上架</el-button
      >
      <el-button size="medium" v-if="detail.status.id == 1" @click="disable"
        >下架</el-button
      >
    </el-row>
    <el-tabs v-model="activeName">
      <el-tab-pane label="商品配置" name="first"></el-tab-pane>
      <el-tab-pane label="操作记录" name="second"></el-tab-pane>
    </el-tabs>
    <!-- 商品图片卡片视图区域 -->
    <el-card v-show="activeName === 'first'">
      <div slot="header">
        <span>商品图片</span>
      </div>
      <el-row>
        <el-col :span="3">banner主图：</el-col>
        <el-col :span="9">
          <el-image
            style="width: 100px; height: 100px"
            fit="cover"
            v-for="(item, index) in detail.cover_url_detail"
            :key="index"
            :src="item"
            :preview-src-list="detail.cover_url_detail"
          ></el-image>
        </el-col>
        <el-col :span="3">banner辅图：</el-col>
        <el-col :span="9">
          <el-image
            style="width: 100px; height: 100px"
            fit="cover"
            v-for="(item, index) in detail.carousel_url_detail"
            :key="index"
            :src="item"
            :preview-src-list="detail.carousel_url_detail"
          ></el-image>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="3">详情图：</el-col>
        <el-col :span="9">
          <el-image
            style="width: 100px; height: 100px"
            fit="cover"
            v-for="(item, index) in detail.details_url_detail"
            :key="index"
            :src="item"
            :preview-src-list="detail.details_url_detail"
          ></el-image>
        </el-col>
        <el-col :span="3">商品icon图标：</el-col>
        <el-col :span="9">
          <el-image
            style="width: 100px; height: 100px"
            fit="cover"
            v-for="(item, index) in detail.icon_url_detail"
            :key="index"
            :src="item"
            :preview-src-list="detail.icon_url_detail"
          ></el-image>
        </el-col>
      </el-row>
    </el-card>
    <!-- 产品配置卡片视图区域 -->
    <el-card v-show="activeName === 'first'">
      <div slot="header">
        <span>产品配置</span>
        <el-button
          type="text"
          style="float: right; padding: 3px 0"
          v-show="detail.status.id != 1"
          @click="openProductEditDialog"
          >编辑产品配置</el-button
        >
      </div>
      <el-table :data="productTableData" border style="width: 100%">
        <el-table-column prop="num" label="编号" width="180"> </el-table-column>
        <el-table-column label="产品类型" width="180">
          <template slot-scope="scope">{{ scope.row.type.name }}</template>
        </el-table-column>
        <el-table-column label="产品【ID】/服务卡【ID】">
          <template slot-scope="scope"
            >{{ scope.row.name }}【{{ scope.row.id }}】</template
          >
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 定价规则卡片视图区域 -->
    <el-card v-show="activeName === 'first'">
      <div slot="header">
        <span>定价规则</span>
        <el-button
          type="text"
          style="float: right; padding: 3px 0"
          v-show="detail.status.id != 1"
          @click="openPriceRuleAddDialog"
          >新增定价规则</el-button
        >
      </div>
      <el-table :data="ruleTableData" border style="width: 100%">
        <el-table-column prop="id" label="定价规则ID" width="180">
        </el-table-column>
        <el-table-column prop="start_time" label="生效日期" width="180">
        </el-table-column>
        <el-table-column prop="end_time" label="失效日期"> </el-table-column>
        <el-table-column prop="price" label="统一价"> </el-table-column>
        <!-- <el-table-column prop="address" label="是否设置差异价">
        </el-table-column> -->
        <el-table-column prop="remark" label="备注"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">{{ scope.row.status.name }}</template>
        </el-table-column>
        <el-table-column label="操作" v-if="detail.status.id != 1">
          <template slot-scope="scope">
            <el-link
              type="danger"
              v-show="scope.row.status.id == 1 || scope.row.status.id == 2"
              @click="closePriceRule(scope.row.id)"
              >关闭</el-link
            >
            &nbsp;
            <el-link
              type="primary"
              v-show="scope.row.status.id == 1 || scope.row.status.id == 2"
              @click="openPriceRuleEditDialog(scope.row)"
              >编辑</el-link
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 操作记录卡片视图区域 -->
    <el-card v-show="activeName === 'second'">
      <el-row>
        <el-timeline>
          <el-timeline-item
            v-for="(item, index) in logData"
            :key="index"
            :timestamp="item.create_time + '【' + item.operator_name + '】'"
            >{{ item.operation_desc }}
          </el-timeline-item>
        </el-timeline>
      </el-row>
    </el-card>

    <!-- 编辑商品信息弹窗 -->
    <el-dialog
      title="编辑"
      :visible.sync="commodityEditDialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <!-- 商品信息表单 -->
      <CommodityBaseInfoEdit
        :commodityData="commodityForm"
        ref="commodityBaseInfoRef"
        @showCommodityBaseInfo="getCommodityBaseInfo"
      ></CommodityBaseInfoEdit>
      <span slot="footer" class="dialog-footer">
        <el-button @click="commodityEditDialogVisible = false">取 消</el-button>
        <el-button class="theme-background-color" @click="saveCommodityData"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 编辑产品配置弹窗 -->
    <el-dialog
      title="编辑产品配置"
      :visible.sync="productEditDialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <!-- 产品配置表格组件 -->
      <ProductConfigure
        :productData="productTable"
        :goodsType="detail.type.id"
        :typeCodes="detail.product_type_codes"
        ref="productConfigureRef"
        @showProductConfig="getProductConfigData"
      ></ProductConfigure>
      <span slot="footer" class="dialog-footer">
        <el-button @click="productEditDialogVisible = false">取 消</el-button>
        <el-button class="theme-background-color" @click="saveProductData"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 新增定价规则弹窗 -->
    <el-dialog
      title="新增定价规则"
      :visible.sync="priceRuleAddDialogVisible"
      width="60%"
      :before-close="priceRuleAddDialogHandleClose"
    >
      <!-- 新增定价规则表格组件 -->
      <PriceRuleAdd
        ref="priceRuleRef"
        @showPriceRuleRef="getPriceRuleRefData"
      ></PriceRuleAdd>
      <span slot="footer" class="dialog-footer">
        <el-button @click="priceRuleAddDialogVisible = false">取 消</el-button>
        <el-button class="theme-background-color" @click="savePriceRuleData"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 编辑定价规则弹窗 -->
    <PriceRuleEdit
      ref="priceRuleEditRef"
      :priceRuleId="priceRuleId"
      :priceRuleEditDialogVisible.sync="priceRuleEditDialogVisible"
    ></PriceRuleEdit>
  </div>
</template>

<script>
import CommodityBaseInfoEdit from './CommodityBaseInfoEdit.vue'
import ProductConfigure from './ProductConfigure.vue'
import PriceRuleAdd from './PriceRuleAdd.vue'
import PriceRuleEdit from './PriceRuleEdit.vue'

export default {
  components: {
    CommodityBaseInfoEdit,
    ProductConfigure,
    PriceRuleAdd,
    PriceRuleEdit
  },
  data() {
    return {
      detail: {
        id: '',
        name: '',
        status: {},
        creator: '',
        class: {},
        type: {},
        stand_price: '',
        product_type_names: '',
        tags: '',
        remark: '',
        cover_url: '',
        carousel_url: [],
        product_type_codes: '',
        details_url: [],
        icon_url: ''
      },
      logData: [],
      //   控制定价规则卡片视图区域的显示与隐藏
      ruleCardVisible: true,
      activeName: 'first',

      productTableData: [],
      activities: [],
      ruleTableData: [],

      // 控制编辑商品弹窗的显示与隐藏
      commodityEditDialogVisible: false,
      commodityForm: {},
      commodityData: {},
      // 控制编辑产品配置弹窗的显示与隐藏
      productEditDialogVisible: false,
      productTable: [],
      productData: [],
      // 控制新增定价规则弹窗的显示与隐藏
      priceRuleAddDialogVisible: false,
      // 定价规则
      priceRuleData: {},

      // 控制编辑定价规则弹窗的显示与隐藏
      priceRuleEditDialogVisible: false,
      // // 定价规则编辑
      // priceRuleEditForm: {},
      // // 差异价规则表编辑
      // diffTableEditData: [],
      priceRuleId: 0
    }
  },
  created() {
    this.getSupplierProductDetail()
    // console.log(this.commodityForm)
  },
  methods: {
    getCommodityBaseInfo(data) {
      this.commodityData = JSON.parse(JSON.stringify(data))
    },
    getProductConfigData(data) {
      this.productData = JSON.parse(JSON.stringify(data))
    },
    getPriceRuleRefData(data) {
      this.priceRuleData = JSON.parse(JSON.stringify(data))
    },
    async getSupplierProductDetail() {
      // 请求数据
      const { data: res } = await this.$http.post('/admin/goods/detail', {
        id: this.$route.query.id
      })

      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.productTableData = res.data.productList
      this.ruleTableData = res.data.ruleList
      this.detail = res.data.goods
      // 处理商品辅图
      this.detail.cover_url_detail = [this.detail.cover_url]
      this.detail.carousel_url_detail = this.detail.carousel_url
        ? this.detail.carousel_url.split(',')
        : []
      this.detail.details_url_detail = this.detail.details_url
        ? this.detail.details_url.split(',')
        : []
      this.detail.icon_url_detail = [this.detail.icon_url]
      // console.log(this.detail)

      this.getLog()
    },
    async getLog() {
      // 请求数据
      const { data: res } = await this.$http.post('/admin/operator_log/list', {
        id: this.$route.query.id
      })
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.logData = res.data
    },
    async enable() {
      // 弹框询问是否启用用户
      const confirmResult = await this.$confirm('确定上架该商品？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消操作')
      }
      const { data: res } = await this.$http.post('/admin/goods/active', {
        id: this.detail.id
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('成功上架')
      this.getSupplierProductDetail()
    },
    disable() {
      // console.log(this.detail.name)
      // 弹框询问是否下架商品
      this.$prompt('确定下架商品【' + this.detail.name + '】吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputPattern: /^(?!.{500}|^\s*$)/g,
        inputErrorMessage: '请输入下架原因',
        closeOnClickModal: false
      })
        .then(async ({ value }) => {
          // console.log(value)
          const { data: res } = await this.$http.post('/admin/goods/close', {
            id: this.detail.id,
            reason: value
          })
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success('成功下架')
          this.getSupplierProductDetail()
        })
        .catch(() => {
          this.$message.info('已取消操作')
        })
    },
    // 打开编辑商品弹窗
    openCommodityDialog() {
      var coverUrlList = []
      for (let i = 0; i < this.detail.cover_url_detail.length; i++) {
        var imageObject = {}
        imageObject.name = ''
        imageObject.url = this.detail.cover_url_detail[i]
        coverUrlList.push(imageObject)
      }
      var carouselUrlList = []
      for (let i = 0; i < this.detail.carousel_url_detail.length; i++) {
        var imageObject = {}
        imageObject.name = ''
        imageObject.url = this.detail.carousel_url_detail[i]
        carouselUrlList.push(imageObject)
      }
      var detailsUrlList = []
      for (let i = 0; i < this.detail.details_url_detail.length; i++) {
        var imageObject = {}
        imageObject.name = ''
        imageObject.url = this.detail.details_url_detail[i]
        detailsUrlList.push(imageObject)
      }
      var iconUrlList = []
      for (let i = 0; i < this.detail.icon_url_detail.length; i++) {
        var imageObject = {}
        imageObject.name = ''
        imageObject.url = this.detail.icon_url_detail[i]
        iconUrlList.push(imageObject)
      }

      this.commodityForm = {
        id: this.detail.id,
        name: this.detail.name,
        type: this.detail.type.id,
        class: this.detail.class.id,
        product_type_codes: this.detail.product_type_codes,
        tags: this.detail.tags,
        remark: this.detail.remark,
        coverUrlList: coverUrlList,
        carouselUrlList: carouselUrlList,
        cover_url: this.detail.cover_url,
        details_url: this.detail.details_url,
        detailsUrlList: detailsUrlList,
        icon_url: this.detail.icon_url,
        iconUrlList: iconUrlList
      }
      // 处理商品分类
      if (parseInt(this.commodityForm.type) == 2) {
        this.commodityForm.product_type_codes =
          this.commodityForm.product_type_codes.split(',')
      }
      // console.log(this.commodityForm)
      this.commodityEditDialogVisible = true
    },
    async saveCommodityData() {
      const flag = await this.$refs.commodityBaseInfoRef.validateForm()
      if (!flag) return
      // console.log(this.commodityData)

      // 向后端发起请求
      const { data: res } = await this.$http.post(
        '/admin/goods/edit',
        this.commodityData
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('编辑商品成功')
      this.getSupplierProductDetail()
      this.commodityEditDialogVisible = false
    },
    openProductEditDialog() {
      // console.log(this.productTableData)
      // var data = []
      // for (let i = 0; i < this.productTableData.length; i++) {
      //   var item = {}
      //   item.id = this.productTableData[i].id
      //   item.type = this.productTableData[i].type.id
      //   item.product = {
      //     id: this.productTableData[i].num,
      //     name: this.productTableData[i].name,
      //     specs: this.productTableData[i].specs
      //   }
      //   item.specs = this.productTableData[i].specs
      //   data.push(item)
      // }
      // console.log(data)
      this.productTable = this.productTableData // data
      this.productEditDialogVisible = true
      // console.log(this.productTable)
    },
    async saveProductData() {
      console.log(this.productData)
      this.$refs.productConfigureRef.getFinalData()
      if (this.productData.length === 0) {
        return this.$message.error('请配置产品')
      }

      // 向后端发起请求
      const { data: res } = await this.$http.post('/admin/goods/edit', {
        id: this.detail.id,
        product: this.productData
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('编辑产品配置成功')
      this.getSupplierProductDetail()
      this.productEditDialogVisible = false
    },
    openPriceRuleAddDialog() {
      this.priceRuleAddDialogVisible = true
    },
    async savePriceRuleData() {
      const flag = this.$refs.priceRuleRef.validateForm()
      if (!flag) return
      this.$refs.priceRuleRef.getFinalData()
      console.log(this.priceRuleData)
      if (this.priceRuleData.is_diff && this.priceRuleData.diff.length === 0) {
        return this.$message.error('请配置差异价规则')
      }
      const postData = Object.assign(this.priceRuleData, {
        goods_id: this.detail.id
      })
      // console.log(this.priceRuleData)
      // 向后端发起请求
      const { data: res } = await this.$http.post(
        '/admin/goods/addPrice',
        postData
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('新增定价规则成功')
      this.getSupplierProductDetail()
      this.priceRuleAddDialogVisible = false
      this.$refs.priceRuleRef.resetAllData()
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    priceRuleAddDialogHandleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          // 清空校验
          this.$refs.priceRuleRef.resetAllData()
          done()
        })
        .catch((_) => {})
    },
    closePriceRule(id) {
      // console.log(this.detail.name)
      // 弹框询问是否关闭定价规则
      this.$prompt('确定关闭定价规则【' + id + '】吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputPattern: /^(?!.{500}|^\s*$)/g,
        inputErrorMessage: '请输入下架原因',
        closeOnClickModal: false
      })
        .then(async ({ value }) => {
          // console.log(value)
          const { data: res } = await this.$http.post('/admin/goods/delPrice', {
            id: id,
            reason: value
          })
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success('成功关闭')
          this.getSupplierProductDetail()
        })
        .catch(() => {
          this.$message.info('已取消操作')
        })
    },
    openPriceRuleEditDialog(row) {
      this.priceRuleId = Number.parseInt(row.id)
      this.priceRuleEditDialogVisible = true
    },
    editPriceRuleData() {},
    productTypeCodes() {
      return parseInt(this.commodityForm.type) === 1
        ? this.commodityForm.classId
        : this.commodityForm.classIds.join(',')
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin: 10px 0;
}
.el-timeline {
  margin-left: -40px;
  width: 100%;
}
</style>
